package com.ymx.darling.dialect;

import com.ymx.darling.bean.sql.BoundSql;
import com.ymx.darling.bean.sql.SqlStatement;
import com.ymx.darling.dialect.keygenerator.KeyGenerator;
import com.ymx.darling.dialect.keygenerator.OracleKeyGenerator;

import java.util.List;

public class OracleDialect implements Dialect{
    private String splitSql(String sql) {
        return "select * from (select ROWNUM AS ROW_NUM, TMP.* from ( "
                + sql +
                " ) TMP WHERE ROWNUM <= ? ) WHERE ROW_NUM > ?";
    }

    @Override
    public String getDataBaseType() {
        return "oracle";
    }

    @Override
    public void paginate(BoundSql boundSql, int pageNum, int pageSize) {
        List<Object> rightParameters = boundSql.getRightParameters();
        int startIndex = pageNum * pageSize;
        int endIndex = (pageNum - 1) * pageSize;
        rightParameters.add(startIndex);
        rightParameters.add(endIndex);

        String pageSql = this.splitSql(boundSql.getSql());
        boundSql.setSql(pageSql);
    }

    @Override
    public void limit(SqlStatement statement, long limit, long offset) {
        List<Object> paramList = statement.getParamList();
        paramList.add(offset + limit);
        paramList.add(offset);
        statement.setSql(this.splitSql(statement.getSql()));
    }

    @Override
    public KeyGenerator getKeyGenerator() {
        return new OracleKeyGenerator();
    }

    @Override
    public String currentTime() {
        return "TO_CHAR(SYSDATE, 'HH24:MI:SS')";
    }

    @Override
    public String charLength(String column) {
        return "LENGTH("+column+")";
    }
}
